package com.zbw.printlibrary.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.zbw.printlibrary.R;
import com.zbw.printlibrary.bean.PrintBTDevice;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.IPrinterControl;
import com.zbw.printlibrary.printConnector.NewPrint;
import com.zbw.printlibrary.util.PrintSharedPreferencesUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.zbw.printlibrary.printConnector.NewPrint.PRINT_BLE;
//import static com.zbw.printlibrary.printSub.PrintBluetooth.isCT;
import static com.zbw.printlibrary.printSub.PrintBluetooth.isConnect;

public class PrintBluetoothActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener,IPrintCallBack {

    private Button ButConnect, ButTest, ButBreak;

    private TextView textTitle;
    private TextView tvTitle;
    private ListView listView1;
    private ArrayAdapter<String> mPairedDevicesAdapter;
    private List<PrintBTDevice> devices;
    private String Address;
    private String BTName;
    private List<String> printList;
    private RelativeLayout rela_layout;
    private TextView tvb_back;
    private IPrinterControl mIPrinterControl;
    private BluetoothAdapter mBluetoothAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏系统通知栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        setContentView(R.layout.activity_print_bluetooth);
        setActivitySize();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_LONG).show();
            return;
        }
        initUi();
    }

    private void initUi() {
        mPairedDevicesAdapter = new ArrayAdapter<String>(this, R.layout.print_device_name);
        ButBreak = findViewById(R.id.ButBreak);
        ButBreak.setOnClickListener(this);
        ButConnect = findViewById(R.id.ButConnect);
        ButConnect.setOnClickListener(this);
        ButTest = findViewById(R.id.ButTest);
        ButTest.setOnClickListener(this);
        textTitle = findViewById(R.id.textTitle);
        listView1 = findViewById(R.id.listView1);
        listView1.setAdapter(mPairedDevicesAdapter);
        listView1.setOnItemClickListener(this);

        tvb_back = (TextView)  findViewById(R.id.tvb_back);
        tvb_back.setOnClickListener(this);

        Address = PrintSharedPreferencesUtils.getParam(PrintBluetoothActivity.this, "addressId", "");
        Log.d("tag", "initUI: " + Address);
        BTName = PrintSharedPreferencesUtils.getParam(this, "bluename", "");
        textTitle.setText(BTName);
    }

    /**
     * 动态设置Activity的大小。
     */
    private void setActivitySize() {
        //动态设置Activity的大小。
        Display display = getWindowManager().getDefaultDisplay(); // 为获取屏幕宽、高
        Window window = getWindow();
        WindowManager.LayoutParams windowLayoutParams = window.getAttributes(); // 获取对话框当前的参数值
        windowLayoutParams.width = (int) (display.getWidth() * 0.6); // 宽度设置为屏幕的0.7
        windowLayoutParams.height = (int) (display.getHeight() * 0.7); // 高度设置为屏幕的0.7
        windowLayoutParams.alpha = 1f;// 设置透明度
        getWindow().setAttributes(windowLayoutParams);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == R.id.tvb_back) {
            //返回
            finish();
        } else if (v.getId() == R.id.ButConnect) {
            //连接
//            if (isCT || !Address.equals("")) {
            if (!"".equals(Address)) {
                if (isConnect) {
                    ButConnect.setText("连接成功");
                    Toast.makeText(this, "已经连接成功", Toast.LENGTH_SHORT).show();
                } else {
                    ButConnect.setText("连接中");
                    if (mIPrinterControl == null) {
                        mIPrinterControl = NewPrint.getInstance().NewControl(PRINT_BLE, PrintBluetoothActivity.this, PrintBluetoothActivity.this);
                        mIPrinterControl.connectPrinter();
                    }
                }
            } else {
                Toast.makeText(this, "请先选择需要连接的打印机", Toast.LENGTH_SHORT).show();
            }
        }else if (v.getId() == R.id.ButTest) {
            try {
                Log.i("蓝牙","==== 4");
                if(isConnect){
                    printList = new ArrayList<>();
                    printList.add("蓝牙打印测试");
                    printList.add("蓝牙打印");
                    printList.add("蓝牙打印");
                    mIPrinterControl.printTest(printList);
                }else{
                    Log.i("蓝牙","==== 6");
                    Toast.makeText(this,"打印机连接中，请稍等",Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("蓝牙","==== 5");
            }

        }else if (v.getId() == R.id.ButBreak) {
            //断开
            if (mIPrinterControl != null) {
                mIPrinterControl.disConnectPrinter();
                mIPrinterControl = null;
            }
        }

    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        if (isConnect) {
            Toast.makeText(this, "请先断开当前连接", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            if (devices != null || devices.size() != 0) {
                textTitle.setText(devices.get(arg2).getName());
                Address = devices.get(arg2).getAddress();
                BTName = devices.get(arg2).getName();
                PrintSharedPreferencesUtils.setParam(this,"addressId",Address);
//                isCT = true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        mPairedDevicesAdapter.clear();
        if (!mBluetoothAdapter.isEnabled()) {
           mBluetoothAdapter.enable();
        }
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            if (devices == null) {
                devices = new ArrayList<PrintBTDevice>();
            }
            devices.removeAll(devices);
            for (BluetoothDevice device : pairedDevices) {
                mPairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
                PrintBTDevice device2 = new PrintBTDevice();
                device2.setName(device.getName());
                device2.setAddress(device.getAddress());
                devices.add(device2);
            }
        } else {
            mPairedDevicesAdapter.add("没有配对的设备");
        }
        mPairedDevicesAdapter.notifyDataSetChanged();
    }

    @Override
    public void onConnect(String message, boolean b) {
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
        if ("连接成功".equals(message)) {
            PrintSharedPreferencesUtils.setParam(this, "bluename", BTName);
            PrintSharedPreferencesUtils.setParam(this, "addressId", Address);
        }else if("连接失败".equals(message)){
            mIPrinterControl = null;
        }
        ButConnect.setText(message);
    }

    @Override
    public void onDisConnect(String message, boolean b) {
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
        if ("断开成功".equals(message)) {
            textTitle.setText("请选择需要连接的打印机");
            ButConnect.setText("连接");
        }else if("断开失败".equals(message)){
        }

    }


    @Override
    public void onPrintResult(final boolean resultCode) {
        Log.i("打印结果",resultCode+"");
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (resultCode) {
                    Toast.makeText(PrintBluetoothActivity.this,"打印成功",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(PrintBluetoothActivity.this,"打印失败",Toast.LENGTH_SHORT).show();

                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //断开
        if (mIPrinterControl != null) {
            mIPrinterControl.disConnectPrinter();
            mIPrinterControl = null;
        }
    }
}
